import { defHttp } from '/@/utils/http/axios';
import { LoginParams, LoginResultModel, GetUserInfoModel } from './model/userModel';
import {encryptByBase64} from '/@/utils/cipher.ts';
import { ErrorMessageMode } from '/#/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useUserStoreWithOut } from '/@/store/modules/user';
import * as authCache from '/@/utils/cache/module/auth';
import { TOKEN_KEY } from '/@/enums/cacheEnum';
import { router } from '/@/router';
import { PageEnum } from '/@/enums/pageEnum';
import qs from 'qs'
import { ConfigEnum } from '/@/enums/httpEnum';
import { useGlobSetting } from '/@/hooks/setting';
import { Api } from '/@/api/url'

const globSetting = useGlobSetting();

const { createErrorModal } = useMessage();

/**
 * 修改用户密码
 * @returns 
 */
export const userResetPassword = (params, handleSuccess) => {
  return defHttp.post({ url: Api.userResetPassword, params }, { isTransformResponse: false }).then((res) => {
    handleSuccess(res);
  });
};


/**
 * 更新用户信息
 * @returns 
 */
export const updateProfile = (params) => {
  return defHttp.post({ url: Api.updateProfile, params });
};


/**
 * @description: user login api
 */
 export function loginApi(params: LoginParams, mode: ErrorMessageMode = 'modal') {
  const { account, password} = params;
  return defHttp.post<LoginResultModel>(
    {
      url: Api.userLogin + "?",
      headers: {
        "Authorization": "Basic " + encryptByBase64(`${globSetting.oauth2ClientId}:test`).toString(),
        'Content-Type': 'application/x-www-form-urlencoded',
        'x-tenant-id': globSetting.platformTenantId
      },
      data: qs.stringify({account, password}),
      params: qs.stringify({
        ...params,
        grant_type: "password",
        scope: "server"
      })
    },
    {
      errorMessageMode: mode,
    }
  );
}

/**
 * @description: user phoneLogin api
 */
export function phoneLoginApi(params: LoginParams, mode: ErrorMessageMode = 'modal') {
  return defHttp.post<LoginResultModel>(
    {
      url: Api.phoneLogin,
      params,
    },
    {
      errorMessageMode: mode,
    }
  );
}

/**
 * @description: getUserInfo
 */
export function getUserInfo() {
  return defHttp.get<GetUserInfoModel>({ url: Api.getUserInfo }, { errorMessageMode: 'message' }).catch((e) => {
    // 捕获接口超时异常,跳转到登录界面
    if (e && (e.message.includes('timeout') || e.message.includes('401'))) {
      //接口不通时跳转到登录界面
      const userStore = useUserStoreWithOut();
      userStore.setToken('');
      authCache.setAuthInfo({ accessToken: undefined });
      router.push(PageEnum.BASE_LOGIN);
    }
  });
}

export function getUserBaseInfo() {
  return defHttp.get<any>({ url: Api.getUserBaseInfo }, { errorMessageMode: 'message' }).catch((e) => {
    // 捕获接口超时异常,跳转到登录界面
    if (e && (e.message.includes('timeout') || e.message.includes('401'))) {
      //接口不通时跳转到登录界面
      const userStore = useUserStoreWithOut();
      userStore.setToken('');
      authCache.setAuthInfo({ accessToken: undefined });
      router.push(PageEnum.BASE_LOGIN);
    }
  });
}


export function doLogout() {
  return defHttp.delete({ url: Api.Logout });
}

/**
 * @description: 注册接口
 */
export async function register(params) {
  const apiParams = {...params}
  return defHttp.post({ url: Api.registerApi, params: apiParams }, { isReturnNativeResponse: true, errorMessageMode: 'none' });
}

/**
 *校验用户是否存在
 * @param params
 */
export const checkOnlyUser = (params) => defHttp.get({ url: Api.checkOnlyUser, params }, { isTransformResponse: false });
/**
 *校验手机号码
 * @param params
 */
export const phoneVerify = (params) => defHttp.post({ url: Api.phoneVerify, params }, { isTransformResponse: false });
/**
 *密码修改
 * @param params
 */
export const passwordChange = (params) => defHttp.get({ url: Api.passwordChange, params }, { isTransformResponse: false });
/**
 * @description: 第三方登录
 */
export function thirdLogin(params, mode: ErrorMessageMode = 'modal') {
  return defHttp.get<LoginResultModel>(
    {
      url: `${Api.thirdLogin}/${params.token}/${params.thirdType}`,
    },
    {
      errorMessageMode: mode,
    }
  );
}
/**
 * @description: 获取第三方短信验证码
 */
export function setThirdCaptcha(params) {
  return new Promise((resolve, reject) => {
    defHttp.post({ url: Api.getThirdCaptcha, params }, { isTransformResponse: false }).then((res) => {
      console.log(res);
      if (res.success) {
        resolve(true);
      } else {
        createErrorModal({ title: '错误提示', content: res.message || '未知问题' });
        reject();
      }
    });
  });
}

/**
 * SSO登录校验
 */
export async function validateCasLogin(params) {
  let url = Api.validateCasLogin;
  return defHttp.get({ url: url, params });
}

/**
 * 
 * @returns 获取当前登录用户所属租户
 */
export async function listTenant(accessToken?: string) {
  const headers = accessToken ? { 'Authorization': 'Bearer ' + accessToken } : { }
  return defHttp.get({ url: Api.listTenant, params: {}, headers});
}

/**
 * 
 * @returns 获取当前登录用户所属租户
 */
export async function listTenantTree(accessToken?: string) {
  const headers = accessToken ? { 'Authorization': 'Bearer ' + accessToken } : {}
  return defHttp.get({ url: Api.listTenantTree, params: {}, headers});
}

export async function selectLoginTenant(params) {
  const headers = {}
  headers[ConfigEnum.TENANT_ID] = params.tenantId
  return defHttp.post({ url: Api.selectLoginTenant, params, headers});
}

export async function switchTenant(params) {
  const headers = {}
  headers[ConfigEnum.TENANT_ID] = params.tenantId
  return defHttp.post({ 
    url: Api.switchTenant, params, headers
  });
}

